package by.grsu.hdm.software;

import java.util.ArrayList;
import java.util.List;

import by.grsu.hdm.exception.EmptyFileSystemException;
import by.grsu.hdm.exception.NonExistentFileIdException;
import by.grsu.hdm.model.Audio;
import by.grsu.hdm.model.IFileSystem;
import by.grsu.hdm.model.IProgram;
import by.grsu.hdm.model.MediaPlayerStatus;
import by.grsu.hdm.model.Program;
import by.grsu.hdm.model.Video;

public class MediaPlayer extends Program implements IProgram {
	
	private boolean isPlaying;
	private int currentFileIndex;
	private List<String> filesQueue = new ArrayList<String>();
	
	protected MediaPlayer() {
		defaultConfiguration();
	}

	public MediaPlayer(String pid) {
		super(pid);
		defaultConfiguration();
	}
	
	private void defaultConfiguration() {
		this.isPlaying = false;
		this.currentFileIndex = 0;
	}
	
	public void setSource(IFileSystem device) throws EmptyFileSystemException {
		if (device.getFilesList().size() == 0) {
			throw new EmptyFileSystemException();
		}
		else {
			filesQueue = device.getFilesList();
		}
	}
	
	public List<String> getFilesQueue() {
		return filesQueue;
	}

	public boolean checkSupportedFormats(String filename) {
		Audio audioSupport = new Audio();
		Video videoSupport = new Video();
		
		String fileExtension = filename.split("\\.")[1];
		
		if  ((audioSupport.checkFormat(fileExtension)) || (videoSupport.checkFormat(fileExtension))) {
			return true;
		}
		else {
			return false;
		}
	}
	
	public MediaPlayerStatus getMediaPlayerStatus() {
		return new MediaPlayerStatus(isPlaying, filesQueue.get(currentFileIndex), currentFileIndex);
	}
	
	public void playById(int id) throws NonExistentFileIdException {
		// transform from id (eg, numbers 1-10) to list index (eg, numbers 0-9)
		id = id - 1;
		
		if((id < 0) || (id >= filesQueue.size())) {
			throw new NonExistentFileIdException();
		}
		else {
			this.currentFileIndex = id;
			this.isPlaying = true;
		}
	}
	
	public void play() {
		if(this.isPlaying) {
			this.isPlaying = false;
		}
		else {
			if (checkSupportedFormats(filesQueue.get(currentFileIndex))) {
				this.isPlaying = true;
			}
			else {
				System.out.println("Current file format is not supported.");
			}
		}
	}
	
	public void playNext() {
		this.isPlaying = false;
		
		if(currentFileIndex == filesQueue.size()-1) {
			currentFileIndex = 0;
		}
		else {
			currentFileIndex = currentFileIndex + 1;
		}
		
		play();
	}
	
	public void playPrevious() {
		this.isPlaying = false;
		
		if(currentFileIndex == 0) {
			currentFileIndex = filesQueue.size()-1;
		}
		else {
			currentFileIndex = currentFileIndex - 1;
		}
		
		play();
	}
}